﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using WebComponents.Data;
using WebComponents;
using WebComponents.Security;
using GBIT.Web;
using System.Collections.Generic;

public partial class ThemSanPham : UserControlBase {
  int productId = 0;
  public string banggia = "";
  protected void Page_Load(object sender, EventArgs e) {
    if (Request.Params["id"] != null)
      productId = ToInt(Request.Params["id"]);
    this.Title = "Sản phẩm";
    this.TaskTitle = "Thêm mới";
    if (!Page.IsPostBack) {
      LoadCategory();
      var product = ProductController.GetByProductID(productId);
      if (product != null) {
        txtTitle.Text = product.ProductName;
        txtContent.Value = product.FullDescription;
        txtOrderId.Text = product.OrderId.ToString();
        this.TaskTitle = "Cập nhật";
        if (cmbNhomSanPham.Items.FindByValue(product.CateID.ToString()) != null)
          cmbNhomSanPham.Items.FindByValue(product.CateID.ToString()).Selected = true;
        if (product.CultureId == "vi-VN")
          cmbLanguage.SelectedIndex = 0;
        else
          cmbLanguage.SelectedIndex = 1;
        ImageThumbnail.ImagePath = product.SmallImageUrl;
        ImageThumbnail.ImageUrl = product.SmallImageUrl;
        ImageFull.ImagePath = product.ImageUrl;
        ImageFull.ImageUrl = product.ImageUrl;
        txtPrice.Text = product.UnitPrice.ToString();
        txtMaSanPham.Text = product.ProductCode;
        txtSoLuongCon.Text = product.Comments;
        txtTrichDan.Value = product.ShortDescription;
        cmbNhaSanXuat.SelectedIndex = -1;
        if (cmbNhaSanXuat.Items.FindByValue(product.ManufacturerID.ToString()) != null)
          cmbNhaSanXuat.Items.FindByValue(product.ManufacturerID.ToString()).Selected = true;
        cmbStatus.SelectedIndex = -1;
        if (cmbStatus.Items.FindByValue(product.StatusID.ToString()) != null)
          cmbStatus.Items.FindByValue(product.StatusID.ToString()).Selected = true;
        var nhomgia = ProductAttributesController.GetByProductID(product.ProductID);
        string gia = "gias = [";
        string soluong = "soluongs = [";
        foreach (ProductAttributesInfo pa in nhomgia) {
          gia += "\"" + pa.AttributeValue1 + "\",";
          soluong += "\"" + pa.AttributeValue + "\",";
        }
        if (gia.EndsWith(","))
          gia = gia.Remove(gia.LastIndexOf(","));
        gia = gia + "]";
        if (soluong.EndsWith(","))
          soluong = soluong.Remove(soluong.LastIndexOf(","));
        soluong = soluong + "]";
        banggia = gia + "\r\n" + soluong;
        //SetAttribute(product.Attributes);
      }
      //else
      //  txtOrderId.Text = ArticleController.MaxOrderId(1).ToString();
    }
    this.SaveEnabled = true;
  }
  protected override void OnSaveRecord(bool redirect) {
    ProductInfo product = null;
    if (productId > 0)
      product = ProductController.GetByProductID(productId);
    if (product == null)
      product = new ProductInfo();
    product.ProductName = txtTitle.Text;
    product.FullDescription = txtContent.Value;
    product.OrderId = ConvertType.ToInt(txtOrderId.Text);
    product.SmallImageUrl = ImageThumbnail.ImagePath;
    product.ImageUrl = ImageFull.ImagePath;
    product.CultureId = cmbLanguage.SelectedValue;
    product.CateID = ToInt(cmbNhomSanPham.SelectedValue);
    product.UnitPrice = ConvertType.ToDecimal(txtPrice.Text);
    product.Comments = txtSoLuongCon.Text;
    product.ProductCode = txtMaSanPham.Text;
    product.ShortDescription = txtTrichDan.Value;
    product.ManufacturerID = ConvertType.ToInt(cmbNhaSanXuat.SelectedValue);
    product.StatusID = ToInt(cmbStatus.SelectedValue);
    //AddProductImage(productId);
    if (productId <= 0) {
      product.AddedDate = DateTime.Now;
      productId = ProductController.Insert(product);
      AddProductGia(productId);
      Security.ShowClientMessage(Page, "Thêm sản phẩm mới thành công", string.Format("?mod={0}", WebComponents.ConvertType.Encode("SanPham/SanPhamList.ascx")));
    } else {
      ProductController.Update(product);
      AddProductGia(productId);
      Security.ShowClientMessage(Page, "Cập nhật thông tin sản phẩm thành công", string.Format("?mod={0}", WebComponents.ConvertType.Encode("SanPham/SanPhamList.ascx")));
    }

  }

  private void AddProductGia(int productId) {
    ProductAttributesController.DeleteAllByProductId(productId);
    string soluong = ToString(Request.Params["txtSoLuong"]);
    string giaban = ToString(Request.Params["txtGia"]);

    if (soluong != "" && giaban != "") {
      ProductAttributesInfo p = new ProductAttributesInfo();
      p.ProductID = productId;
      p.AttributeValue = soluong;
      p.AttributeValue1 = giaban;
      ProductAttributesController.Insert(p);
    }
    for (int i = 0; i < 20; i++) {
      soluong = ToString(Request.Params["txtSoLuong$" + i.ToString()]);
      giaban = ToString(Request.Params["txtGia$" + i.ToString()]);
      if (soluong != "" && giaban != "") {
        ProductAttributesInfo p = new ProductAttributesInfo();
        p.ProductID = productId;
        p.AttributeValue = soluong;
        p.AttributeValue1 = giaban;
        ProductAttributesController.Insert(p);
      }
    }
  }

  private void SetAttribute(string attributes) {
    //XMLHelper xml = new XMLHelper();
    //xml.CreateDocument(attributes);
    //foreach (Control c in rptColorItem.Controls) {
    //  HtmlInputText txtMoTa = c.FindControl("txtMota") as HtmlInputText;
    //  if (txtMoTa != null) {
    //    txtMoTa.Value = xml.GetValue("product/Cate" + txtMoTa.Attributes["title"]);
    //  }
    //}
  }

  protected void LoadCategory() {
    this.cmbNhomSanPham.Items.Clear();
    this.cmbNhomSanPham.Items.Add("");
    Global.LoadCategory(cmbLanguage.SelectedValue, ref cmbNhomSanPham, CatetoryType.Product);
    this.cmbNhaSanXuat.Items.Clear();
    this.cmbNhaSanXuat.Items.Add("");
    foreach (ManufacturerInfo mu in ManufacturerController.List()) {
      this.cmbNhaSanXuat.Items.Add(new ListItem(mu.ManufacturerVi, mu.ManufacturerID.ToString()));
    }
  }
  protected void cmbLanguage_SelectedIndexChanged(object sender, EventArgs e) {
    LoadCategory();
  }
  protected void rptColorItem_ItemDataBound(object sender, RepeaterItemEventArgs e) {
    CategoryInfo cate = e.Item.DataItem as CategoryInfo;
    if (cate != null) {
      var list = ColorController.GetByCateID(cate.CategoryID);
      DataList dataList = e.Item.FindControl("dtlColorItem") as DataList;
      dataList.DataSource = list;
      dataList.DataBind();
    }
  }
}
